package classign.election.kingvar.come.electionclasssign.activity;

import android.content.Context;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;

import com.squareup.leakcanary.LeakCanary;

import org.greenrobot.greendao.database.Database;

import classign.election.kingvar.come.electionclasssign.api.RetrofitService;
import classign.election.kingvar.come.electionclasssign.greendao.DaoMaster;
import classign.election.kingvar.come.electionclasssign.greendao.DaoSession;
import classign.election.kingvar.come.electionclasssign.injector.components.ApplicationComponent;
import classign.election.kingvar.come.electionclasssign.injector.components.DaggerApplicationComponent;
import classign.election.kingvar.come.electionclasssign.injector.modules.ApplicationModule;
import classign.election.kingvar.come.electionclasssign.rxbus.RxBus;
import classign.election.kingvar.come.electionclasssign.tools.utils.ToastUtils;

/**
 * Generated application for tinker life cycle
 */
public class MyApplication extends MultiDexApplication {

    private static ApplicationComponent sAppComponent;
    private static final String DB_NAME = "member-db";
    private DaoSession mDaoSession;
    private RxBus mRxBus = new RxBus();
    public static MyApplication instance;


    @Override
    public void onCreate() {
        super.onCreate();
		instance = this;

        initDB();
        _initInjector();
        _initConfig();
        _ininLeakCanary();
//        _initFirBug();

    }
/*
    private void _initFirBug() {
        FIR.init(this);
    }*/

    public static MyApplication getInstance() {
        return instance;
    }
    private void _ininLeakCanary() {
        LeakCanary.install(this);
    }

    /**
     * 使用Tinker生成Application，这里改成静态调用
     *
     * @return
     */
    public static ApplicationComponent getAppComponent() {
        return sAppComponent;
    }

    /**
     * 初始化注射器
     */
    private void _initInjector() {
        // 这里不做注入操作，只提供一些全局单例数据
        sAppComponent = DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule(this, mDaoSession, mRxBus))
                .build();
    }

    private void initDB() {
        //初始化数据库
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, DB_NAME);
        Database db = helper.getWritableDb();
        mDaoSession = new DaoMaster(db).newSession();

    }

    public DaoSession getDaoSession() {
        return mDaoSession;
    }

    /**
     * 初始化配置
     */
    private void _initConfig() {
        RetrofitService.init();
        ToastUtils.init(getInstance());
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}